package stack_quene.stack.quene.impl;

import stack_quene.stack.quene.Queue;

import java.util.NoSuchElementException;

public class LinkedQuene implements Queue {
    private Node head;
    private Node tail;
    private int size;
    private class Node{
        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
        }
    }

    /**
     * 队首出，队尾进
     * @param value
     */
    @Override
    public void offer(int value) {
        Node node=new Node(value);
        if(head==null){
            head=tail=node;
        }else {
            tail.next = node;
            tail = node;
        }
        size++;
    }

    //出队列操作
    @Override
    public int poll() {
        if(size==0){
            throw new NoSuchElementException("队列为空");
        }
        int oldValue=head.data;
        Node node=head;
        head=head.next;
        node.next=null;
        size--;
        return oldValue;
    }

    //查看队首元素，但不删除的操作
    @Override
    public int peek() {
        if(size==0){
            throw new NoSuchElementException("队列为空");
        }
        return head.data;
    }


    @Override
    public boolean isEmpty() {
        return false;
    }

    //打印输出队列
    @Override
    public String toString() {
       StringBuilder stringBuilder=new StringBuilder();
       stringBuilder.append("front [");
        Node node=head;
        while(node!=null){
            stringBuilder.append(node.data);
            if(node.next!=null){
                stringBuilder.append(",");
            }
            node=node.next;
        }
        stringBuilder.append("] top");
        return stringBuilder.toString();
    }
}
